package logic

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"go-exp/query"
	"go-exp/zero/rpc/user/internal/svc"
	"go-exp/zero/rpc/user/pb/user"
	"google.golang.org/grpc/metadata"
)

type GetUserByUsernameLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetUserByUsernameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserByUsernameLogic {
	return &GetUserByUsernameLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetUserByUsernameLogic) GetUserByUsername(in *user.GetUserByUsernameRequest) (*user.User, error) {
	md, ok := metadata.FromIncomingContext(l.ctx)
	if ok {
		// 提取 Metadata 中的数据
		if traceIDs := md.Get("userId"); len(traceIDs) > 0 {
			logx.Error("userId: ", traceIDs[0])
		}
	}
	q := query.SysUser
	first, _ := q.WithContext(l.ctx).Where(q.Username.Eq(in.Username)).First()
	logx.Infof("where: %v", first)
	if first == nil {
		return nil, nil
	}
	return &user.User{
		Id:        first.ID,
		Username:  first.Username,
		Password:  first.PasswordHash,
		CreatedAt: first.CreatedAt.Format("2006-01-02 15:04:05"),
	}, nil
}
